﻿(function ($, undefined) {
    $.widget("ui.mediaUploadButton", {
        options: {
            action: '',
            mediaName: '',
            data: {},
            responseType: 'json',
            callback: function () { }
        },
        _create: function () {
            var $this = this;
            var element = $(this.element);

            // the id for the result iframe 
            var frameId = $.trim(element.attr('id'));
            if (frameId.length == 0) {
                frameId = 'mub';
            }

            frameId = 'frame' + frameId + '_' + new Date().getTime();

            // the iframe to receive the result
            var resultFrame = $('<iframe style="display:none; width: 0; height: 0; border: none;"></iframe>')
                .appendTo('body')
                .attr({
                    'id': frameId,
                    'name': frameId
                });

            resultFrame.load(function () {
                $('#throbber').hide();

                if ($this.options.callback) {
                    var doc = resultFrame.contents()[0];

                    // fixing Opera 9.26,10.00
                    if (doc.readyState && doc.readyState != 'complete') {
                        // Opera fires load event multiple times
                        // Even when the DOM is not ready yet
                        // this fix should not affect other browsers
                        return;
                    }

                    // fixing Opera 9.64
                    if (doc.body && doc.body.innerHTML == "false") {
                        // In Opera 9.64 event was fired second time
                        // when body.innerHTML changed from false 
                        // to server response approx. after 1 sec
                        return;
                    }

                    var response;

                    if (doc.XMLDocument) {
                        // response is a xml document Internet Explorer property
                        response = doc.XMLDocument;
                    } else if (doc.body) {
                        // response is html document or plain text
                        response = doc.body.innerHTML;

                        if ($this.options.responseType && $this.options.responseType.toLowerCase() == 'json') {
                            // If the document was sent as 'application/javascript' or
                            // 'text/javascript', then the browser wraps the text in a <pre>
                            // tag and performs html encoding on the contents.  In this case,
                            // we need to pull the original text content from the text node's
                            // nodeValue property to retrieve the unmangled content.
                            // Note that IE6 only understands text/html
                            if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {
                                response = doc.body.firstChild.firstChild.nodeValue;
                            }

                            if (response) {
                                response = eval("(" + response + ")");
                            } else {
                                response = {};
                            }
                        }
                    } else {
                        // response is a xml document
                        response = doc;
                    }
                    $this.options.callback(response);
                    //settings.onComplete.call(self, file, response);
                    
                    // Fix IE mixed content issue
                    resultFrame.src = "javascript:'<html></html>';";
                    
                }

                // re - create the form
                $this._createForm(resultFrame, element);
            });

            // the form to post the media
            $this._createForm(resultFrame, element);

        },

        _createForm: function (resultFrame, element) {
            var form = $('<form></form>')
                //.appendTo('body')
                .appendTo(resultFrame.contents().find('body'))
                .attr({
                    'action': this.options.action,
                    'method': 'post',
                    "enctype": "multipart/form-data",
                    'target': '_self'//frameId
                });

            var contentContainer = $('<div id="formContent" style="display:none;"></div>')
                .appendTo(form);

            var mediaName = $.trim(this.options.mediaName);
            if (mediaName.length == 0) mediaName = element.attr('id');

            var inputFile = $('<input type="file"/>')
                .appendTo(contentContainer)
                .attr('name', mediaName)
                .change(function () {
                    $('#throbber').show();
                    form.submit();
                });

            if (this.options.data) {
                $.each(this.options.data, function (key, value) {
                    $('<input type="hidden"/>')
                        .appendTo(contentContainer)
                        .attr({
                            'name': key,
                            'value': value
                        });
                });
            }

            // forward the click event of the element to the inputFile
            element.click(function () {
                inputFile.click();
            });
        },

        destroy: function () {
            
        }
    });

    $.extend($.ui.mediaUploadButton, {
        version: "0.1.0"
    });
})(jQuery);